package com.example.huixue.controller;

import com.example.huixue.common.Result;
import com.example.huixue.entity.Resource;
import com.example.huixue.service.ResourceService;
import com.example.huixue.util.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin(origins = "*", maxAge = 3600)
public class ResourceController {
    
    private static final Logger logger = LoggerFactory.getLogger(ResourceController.class);
    
    @Autowired
    private ResourceService resourceService;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    /**
     * 从token中获取用户ID
     */
    private Long getUserIdFromToken(String token) {
        if (token == null || !token.startsWith("Bearer ")) {
            return null;
        }
        
        try {
            String jwtToken = token.substring(7);
            
            if (!jwtUtil.validateToken(jwtToken)) {
                return null;
            }
            
            Integer userIdInt = jwtUtil.getUserIdFromToken(jwtToken);
            return userIdInt != null ? Long.valueOf(userIdInt) : null;
        } catch (Exception e) {
            logger.warn("解析token失败: {}", e.getMessage());
            return null;
        }
    }
    
    /**
     * 分页查询资源
     */
    @GetMapping({"/resources", "/api/resources"})
    public Result<?> getResources(@RequestParam(defaultValue = "1") int page,
                                  @RequestParam(defaultValue = "12") int size,
                                  @RequestParam(required = false) String keyword,
                                  @RequestParam(required = false) Long categoryId,
                                  @RequestParam(required = false) String fileType,
                                  @RequestParam(defaultValue = "uploadTime") String sortBy) {
        try {
            logger.info("分页查询资源请求: page={}, size={}, keyword={}, categoryId={}", page, size, keyword, categoryId);
            return Result.success("获取资源成功", resourceService.getResourcesWithPagination(page, size, keyword, categoryId, fileType, sortBy));
        } catch (Exception e) {
            logger.error("获取资源失败", e);
            return Result.error("获取资源失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据ID获取资源详情
     */
    @GetMapping({"/resources/{resourceId}", "/api/resources/{resourceId}"})
    public Result<?> getResourceById(@PathVariable Long resourceId) {
        try {
            logger.info("获取资源详情请求: resourceId={}", resourceId);
            return Result.success("获取资源详情成功", resourceService.getResourceById(resourceId));
        } catch (Exception e) {
            logger.error("获取资源详情失败", e);
            return Result.error("获取资源详情失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取相关资源推荐
     */
    @GetMapping({"/resources/{resourceId}/related", "/api/resources/{resourceId}/related"})
    public Result<?> getRelatedResources(@PathVariable Long resourceId) {
        try {
            logger.info("获取相关资源请求: resourceId={}", resourceId);
            List<?> relatedResources = resourceService.getRelatedResources(resourceId);
            return Result.success("获取相关资源成功", relatedResources);
        } catch (Exception e) {
            logger.error("获取相关资源失败", e);
            return Result.error("获取相关资源失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取热门资源（下载最多、收藏最多、阅读最多的各一个）
     */
    @GetMapping({"/resources/popular", "/api/resources/popular"})
    public Result<?> getPopularResources() {
        try {
            logger.info("获取热门资源请求");
            List<?> popularResources = resourceService.getPopularResources(3);
            return Result.success("获取热门资源成功", popularResources);
        } catch (Exception e) {
            logger.error("获取热门资源失败", e);
            return Result.error("获取热门资源失败：" + e.getMessage());
        }
    }
    
    /**
     * 增加资源浏览量
     */
    @PostMapping({"/resources/{resourceId}/view", "/api/resources/{resourceId}/view"})
    public Result<?> incrementViewCount(@PathVariable Long resourceId) {
        try {
            logger.info("增加浏览量请求: resourceId={}", resourceId);
            resourceService.incrementViewCount(resourceId);
            return Result.success("浏览量增加成功");
        } catch (Exception e) {
            logger.error("增加浏览量失败", e);
            return Result.error("增加浏览量失败：" + e.getMessage());
        }
    }
    
    /**
     * 下载资源
     */
    @GetMapping({"/resources/{resourceId}/download", "/api/resources/{resourceId}/download"})
    public Result<?> downloadResource(@PathVariable Long resourceId,
                                     @RequestHeader(value = "Authorization", required = false) String token) {
        try {
            logger.info("下载资源请求: resourceId={}", resourceId);
            
            // 从token获取用户ID，如果没有token使用默认用户ID
            Long userId = getUserIdFromToken(token);
            if (userId == null) {
                userId = 1L; // 默认用户ID（游客下载）
            }
            
            // 记录下载统计
            resourceService.recordDownload(resourceId, userId);
            
            // 这里应该返回文件流，暂时返回成功信息
            return Result.success("文件下载成功");
        } catch (Exception e) {
            logger.error("下载资源失败", e);
            return Result.error("下载资源失败：" + e.getMessage());
        }
    }
    
    /**
     * 用户上传资源
     */
    @PostMapping({"/resources/upload", "/api/resources/upload"})
    public Result<?> userUploadResource(@RequestParam("file") MultipartFile file,
                                       @RequestParam("title") String title,
                                       @RequestParam("description") String description,
                                       @RequestParam("categoryId") Long categoryId,
                                       @RequestHeader(value = "Authorization", required = false) String token) {
        try {
            logger.info("用户上传资源请求: title={}, categoryId={}", title, categoryId);
            
            if (file.isEmpty()) {
                return Result.error("请选择要上传的文件");
            }
            
            // 从token获取用户ID
            Long userId = getUserIdFromToken(token);
            if (userId == null) {
                return Result.error("请先登录");
            }
            
            Resource resource = resourceService.uploadResource(file, title, description, categoryId, userId);
            return Result.success("资源上传成功", resource);
        } catch (Exception e) {
            logger.error("用户上传资源失败", e);
            return Result.error("上传资源失败：" + e.getMessage());
        }
    }
    
    /**
     * 管理员上传资源
     */
    @PostMapping({"/admin/resources/upload", "/api/admin/resources/upload"})
    public Result<?> adminUploadResource(@RequestParam("file") MultipartFile file,
                                        @RequestParam("title") String title,
                                        @RequestParam("description") String description,
                                        @RequestParam("categoryId") Long categoryId,
                                        @RequestHeader(value = "Authorization", required = false) String token) {
        try {
            logger.info("管理员上传资源请求: title={}, categoryId={}", title, categoryId);
            
            if (file.isEmpty()) {
                return Result.error("请选择要上传的文件");
            }
            
            // 从token获取用户ID
            Long userId = getUserIdFromToken(token);
            if (userId == null) {
                userId = 1L; // 管理员默认ID
            }
            
            Resource resource = resourceService.uploadResource(file, title, description, categoryId, userId);
            return Result.success("资源上传成功", resource);
        } catch (Exception e) {
            logger.error("管理员上传资源失败", e);
            return Result.error("上传资源失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新资源信息
     */
    @PutMapping({"/admin/resources/{resourceId}", "/api/admin/resources/{resourceId}"})
    public Result<?> updateResource(@PathVariable Long resourceId, @RequestBody Resource resource) {
        try {
            logger.info("更新资源请求: resourceId={}", resourceId);
            resource.setResourceId(resourceId);
            Resource updatedResource = resourceService.updateResource(resource);
            return Result.success("资源更新成功", updatedResource);
        } catch (Exception e) {
            logger.error("更新资源失败", e);
            return Result.error("更新资源失败：" + e.getMessage());
        }
    }
    
    /**
     * 管理员分页查询资源（包含所有状态）
     */
    @GetMapping("/api/admin/resources")
    public Result<?> getAdminResources(@RequestParam(defaultValue = "1") int page,
                                       @RequestParam(defaultValue = "20") int size,
                                       @RequestParam(required = false) String keyword,
                                       @RequestParam(required = false) Long categoryId,
                                       @RequestParam(required = false) String status,
                                       @RequestParam(required = false) String fileType,
                                       @RequestParam(defaultValue = "uploadTime") String sortBy,
                                       @RequestParam(defaultValue = "desc") String sortOrder) {
        try {
            logger.info("管理员分页查询资源请求: page={}, size={}, keyword={}, status={}", page, size, keyword, status);
            return Result.success("获取资源成功", resourceService.getAdminResourcesWithPagination(page, size, keyword, categoryId, fileType, status, sortBy));
        } catch (Exception e) {
            logger.error("管理员获取资源失败", e);
            return Result.error("获取资源失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取资源统计信息
     */
    @GetMapping("/api/admin/resources/stats")
    public Result<?> getResourceStats() {
        try {
            logger.info("获取资源统计信息请求");
            Map<String, Object> stats = resourceService.getResourceStats();
            return Result.success("获取统计信息成功", stats);
        } catch (Exception e) {
            logger.error("获取统计信息失败", e);
            return Result.error("获取统计信息失败：" + e.getMessage());
        }
    }
    
    /**
     * 管理员审核资源
     */
    @PutMapping("/api/admin/resources/{resourceId}/approve")
    public Result<?> approveResource(@PathVariable Long resourceId) {
        try {
            logger.info("审核通过资源请求: resourceId={}", resourceId);
            resourceService.approveResource(resourceId);
            return Result.success("资源审核通过");
        } catch (Exception e) {
            logger.error("审核资源失败", e);
            return Result.error("审核资源失败：" + e.getMessage());
        }
    }
    
    /**
     * 管理员拒绝资源
     */
    @PutMapping("/api/admin/resources/{resourceId}/reject")
    public Result<?> rejectResource(@PathVariable Long resourceId, @RequestBody Map<String, String> reason) {
        try {
            logger.info("审核拒绝资源请求: resourceId={}", resourceId);
            resourceService.rejectResource(resourceId, reason.get("reason"));
            return Result.success("资源审核拒绝");
        } catch (Exception e) {
            logger.error("拒绝资源失败", e);
            return Result.error("拒绝资源失败：" + e.getMessage());
        }
    }
    
    /**
     * 管理员删除资源
     */
    @DeleteMapping("/api/admin/resources/{resourceId}")
    public Result<?> deleteResource(@PathVariable Long resourceId) {
        try {
            logger.info("删除资源请求: resourceId={}", resourceId);
            resourceService.deleteResource(resourceId);
            return Result.success("资源删除成功");
        } catch (Exception e) {
            logger.error("删除资源失败", e);
            return Result.error("删除资源失败：" + e.getMessage());
        }
    }
    
    /**
     * 批量审核通过资源
     */
    @PutMapping("/api/admin/resources/batch-approve")
    public Result<?> batchApproveResources(@RequestBody Map<String, Object> requestData) {
        try {
            logger.info("批量审核通过资源请求");
            
            @SuppressWarnings("unchecked")
            java.util.List<Object> rawIds = (java.util.List<Object>) requestData.get("ids");
            
            if (rawIds == null || rawIds.isEmpty()) {
                return Result.error("资源ID列表不能为空");
            }
            
            // 转换ID类型
            java.util.List<Long> ids = rawIds.stream()
                .map(id -> Long.valueOf(id.toString()))
                .collect(java.util.stream.Collectors.toList());
            
            resourceService.batchApproveResources(ids);
            logger.info("批量审核通过资源成功: {}", ids);
            return Result.success("批量审核通过成功");
        } catch (Exception e) {
            logger.error("批量审核通过资源失败", e);
            return Result.error("批量审核通过失败：" + e.getMessage());
        }
    }
    
    /**
     * 批量拒绝资源
     */
    @PutMapping("/api/admin/resources/batch-reject")
    public Result<?> batchRejectResources(@RequestBody Map<String, Object> requestData) {
        try {
            logger.info("批量拒绝资源请求");
            
            @SuppressWarnings("unchecked")
            java.util.List<Object> rawIds = (java.util.List<Object>) requestData.get("ids");
            
            if (rawIds == null || rawIds.isEmpty()) {
                return Result.error("资源ID列表不能为空");
            }
            
            // 转换ID类型
            java.util.List<Long> ids = rawIds.stream()
                .map(id -> Long.valueOf(id.toString()))
                .collect(java.util.stream.Collectors.toList());
            
            resourceService.batchRejectResources(ids);
            logger.info("批量拒绝资源成功: {}", ids);
            return Result.success("批量拒绝成功");
        } catch (Exception e) {
            logger.error("批量拒绝资源失败", e);
            return Result.error("批量拒绝失败：" + e.getMessage());
        }
    }
    
    /**
     * 批量删除资源
     */
    @DeleteMapping("/api/admin/resources/batch-delete")
    public Result<?> batchDeleteResources(@RequestBody Map<String, Object> requestData) {
        try {
            logger.info("批量删除资源请求");
            
            @SuppressWarnings("unchecked")
            java.util.List<Object> rawIds = (java.util.List<Object>) requestData.get("ids");
            
            if (rawIds == null || rawIds.isEmpty()) {
                return Result.error("资源ID列表不能为空");
            }
            
            // 转换ID类型
            java.util.List<Long> ids = rawIds.stream()
                .map(id -> Long.valueOf(id.toString()))
                .collect(java.util.stream.Collectors.toList());
            
            resourceService.batchDeleteResources(ids);
            logger.info("批量删除资源成功: {}", ids);
            return Result.success("批量删除成功");
        } catch (Exception e) {
            logger.error("批量删除资源失败", e);
            return Result.error("批量删除失败：" + e.getMessage());
        }
    }
} 